package com.hdax.dm.listener;

import com.hdax.dm.feign.SeatFeign;
import com.hdax.dm.service.OrderLinkUserService;
import com.hdax.dm.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RabbitListener(queues = {"dm_orderLinkUser_rollback","dm_order_rollback","dm_seat_rollback"})
@Component
public class RollbackRabbitListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderLinkUserService orderLinkUserService;

    @Autowired
    private SeatFeign seatFeign;


    //订单联系人新增失败的数据汇滚
    @RabbitHandler
    public void rollbackLinkUser(Channel channel, Message message, String orderNo) throws IOException {

        redisTemplate.delete("lock");

        String queue = message.getMessageProperties().getConsumerQueue();
        //每个队列都有唯一编号，用tag来获取
        long tag = message.getMessageProperties().getDeliveryTag();

        if(queue.equals("dm_orderLinkUser_rollback")){
            Integer flag = orderLinkUserService.orderLinkUserDel(orderNo);
            if (flag>0) {
                //手动确认消息  b ---  true：小于获取编号的都被确认  false：只消费自己
                channel.basicAck(tag,false);
            }else {
//               //拒绝消费、消息  b1 --- false：不希望再消费了，消失  true：下次还想重新消费就写true，重回Ready队列
                channel.basicNack(tag,false,false);
            }
        }else if(queue.equals("dm_order_rollback")){
            Integer flag = orderService.orderDel(orderNo);
            if (flag>0) {
                channel.basicAck(tag,false);
            }else {
                channel.basicNack(tag,false,false);
            }
        }else if(queue.equals("dm_seat_rollback")){
            boolean flag = seatFeign.ishaveSeatUpdate(1L,orderNo);
            if (flag) {
                channel.basicAck(tag,false);
            }else {
                channel.basicNack(tag,false,false);
            }
        }
    }
}
